<template>
	<div>
		<head-top></head-top>	
		<div class="boxWrap col-sm-12">			
			<div class="buildStep">
				<!--显示创建成功-->
				<div class="alert alert-success" v-if="createSuccess" style="background-color: #dff0d8;">
					<a href="#" class="close" data-dismiss="alert">&times;</a>
					<strong>创建成功！</strong>
				</div>
				<div class="alert alert-danger" v-if="createError" style="background-color: #f2dede;">
					<a href="#" class="close" data-dismiss="alert">&times;</a>
					<strong>创建失败！</strong>
				</div>
				<div class="col-sm-12 create_header">
					<img src="../../assets/img/createTask.svg" alt="img" class="col-sm-1"/>
					<div class="col-sm-11 text-left" v-if="pagestate == -1">
						<h5>手动建模</h5>
						<p class="create_words">
							AtomPai不仅支持快速便捷的智能建模，而且还支持更加定制化的建模方式--手动建模。通过手动建模，你可以自由选择你需要训练的模型，
							有针对性地进行参数设置，从而获得符合你预期的预测模型。
						</p>
					</div>
					<div class="col-sm-11 text-left" v-else-if="pagestate == -2">
						<h5>数据预测</h5>
						<p class="create_words">
							预测报告展示了模型运行预测过程后的结果，反映了训练好的模型在测试集上的表现。预测包括包含了对测试数据的基本描述，
							以及相应的可视化图表，比如散点图反应测试数据的分布情况，silhouette图评价了分类预测结果的优劣程度。
						</p>
					</div>
				</div>
			</div>
			<div class="col-sm-12 text-left create_tip_words create_words">
				<p class="buildStep text-center">					
					<strong>第一步：</strong>选择数据源；<strong>第二步：</strong>选择模型；
					<strong>第三步：</strong>选择要用的数据列并进行相应设置；<strong>第四步：</strong>提交计算任务。
				</p>
			</div>
			<div class="buildStep">
				<!--选择数据-->
				<div class="col-sm-12" style="padding:0;">
					<div class="col-sm-6 plat_data" style="padding-right:24px;">
						<div class="create_data_source text-left">
							<p>
								<img src="../../assets/img/create_data_source.svg" alt="img" class="create_svg_size"/>
								<span class="plate_title">数据源</span>								
							</p>
							<p class="text-right choose_right_tip"  v-show="successDataTip">
								<img src="../../assets/img/chooseRight.svg" alt="img" />
								<span>选择数据成功</span>
							</p>
							<p class="create_words_light">选择你希望使用的数据</p>
							<p class="page"><span class="page_one">1</span><span class="page_two">/3</span></p>
							<div class="text-center">
								<p>已选数据</p>
								<p class="select_name" :title="details.title">{{details.title}}</p>
							</div>
							<div class="plat_bottom_part text-center">
								<p>
									<span class="build_name_words font16 build_des_info">&nbsp;&nbsp;&nbsp;上传者:</span>
									<span class="build_des_info" :title="details.creator">{{details.creator}}</span>
									<span class="build_name_words font16">行:</span>
									<span class="build_des_info" :title="details.line_number">{{details.line_number}}</span>
								</p>
								<p>
									<span class="build_name_words font16 build_des_info">上传时间:</span>
									<span class="build_des_info" :title="details.create_time">{{details.create_time}}</span>
									<span class="build_name_words font16">列:</span>
									<span class="build_des_info" :title="details.column_number">{{details.column_number}}</span>
								</p>
							</div>
							<p class="parameter_setting text-center" @click="showDataList()"><span>重新选择</span></p>
						</div>
					</div>
					<!--模型-->
					<div class="col-sm-6 plat_model">						
						<div class="create_data_source text-left">
							<p>
								<img src="../../assets/img/create_model_source.svg" alt="img" class="create_svg_size"/>
								<span class="plate_title">模型选择</span>								
							</p>
							<p class="text-right choose_right_tip" v-show="successModelTip">
								<img src="../../assets/img/chooseRight.svg" alt="img" />
								<span>选择模型成功</span>
							</p>
							<p class="create_words_light">选择你希望使用的模型</p>
							<p class="page"><span class="page_one">2</span><span class="page_two">/3</span></p>
							<!--如果没有选择模型则显示如下-->
							<div v-if="no_choose">
								<p class="text-center no_choose_model_img cursor"  @click="showModelList()">
									<img src="../../assets/img/create_choose_model.svg" alt="img" />
								</p>
								<p class="parameter_setting text-center" @click="showModelList()"><span>选择模型</span></p>
							</div>
							<!--如果已经选择模板则显示如下-->
							<div v-if="already_chosen">								
								<div class="text-center">
									<p>已选模型</p>
									<p class="select_name" :title="model_tem_details.name">{{model_tem_details.name}}</p>
								</div>
								<div class="plat_bottom_part text-center">
									<p>
										<span class="build_name_words font16 build_des_info">&nbsp;&nbsp;&nbsp;创建者:</span>
										<span class="build_des_info" :title="model_tem_details.creator">{{model_tem_details.creator}}</span>
										<span class="build_name_words font16">需要标签列表:</span>
										<span class="build_des_info" :title="model_tem_details.label_number">{{model_tem_details.label_number}}</span>
									</p>
									<p>
										<span class="build_name_words font16 build_des_info">创建时间:</span>
										<span class="build_des_info" :title="model_tem_details.create_time">{{model_tem_details.create_time}}</span>
										<span class="build_name_words font16">需要特征列数:</span>
										<span class="build_des_info" :title="model_tem_details.feature_number">{{model_tem_details.feature_number}}</span>
									</p>
								</div>
								<p class="parameter_setting text-center" @click="showModelList()"><span>重新选择</span></p>
							</div>
						</div>
					</div>
				</div>
				<div class="col-sm-12 run_setup" v-show="runStepThree">
					<div class="run_setup_con text-left">						
						<p>
							<img src="../../assets/img/create_run_setup.svg" alt="img" class="create_svg_size"/>
							<span class="plate_title">运行配置</span>								
						</p>
						<p class="create_words_light">选择建模要使用的标签及特征列，并进行缺失值处理方式等设置</p>	
						<p class="page"><span class="page_one">3</span><span class="page_two">/3</span></p>
						<!--拖拽选择数据至右侧-->
						<dragSpe :features_detail="model_tem_details.features_detail" :col_detail="details.col_detail" v-if="drag_predict"></dragSpe>
						<selectCol :label_detail="model_tem_details.label_detail" :col_detail="details.col_detail" v-if="drag_manual"></selectCol>
						<!--定制缺失值等-->
						<div class="col-sm-12">
							<div class="col-sm-3"></div>
							<div class="col-sm-6">							
								<p class="text-left col-sm-6">
									<span style="font-size:12px;color: rgba(26,44,74,0.30);">不勾选默认采取删除包含缺失值的数据行</span>
									<label class="input_label_beautify">				
								        <input class="input_checkbox" type="checkbox" name="build_checkbox"  v-model="check_miss_val" @change="showCustom()">
								        <span class="input_checkboxInput"></span>定制缺失值处理方式</br>
									</label></br>
				            		<select name="selectPretreatment" style="height:30px;font-size:14px;margin-top:20px;" v-model="selected" v-show="missVal">
				            			<option v-for="option in options" v-bind:value="option.value">{{ option.text }}</option>	            		
				            		</select >
				            	</p>
								<div class="col-sm-6 text-left">
									<span style="font-size:12px;opacity:0;">不勾选默认采取删除包含缺失值的数据行</span>
									<label class="input_label_beautify">				
								        <input class="input_checkbox" type="checkbox" name="build_checkbox" v-model="check_only_data" @change="showCustomData()">
								        <span class="input_checkboxInput"></span>仅使用部分数据
									</label>
									</br>
									<p style="margin-top:20px;" v-show="onlyData">											
										<span>从</span>
										<input type="number" style="width:66px;" v-model="data_begin"/>
										<span>行</span>
										<span>至</span>
										<input type="number" :placeholder="details.line_number" style="width:66px;" v-model="data_end"/>
										<span>行</span>
									</p>
								</div>
							</div>
							<div class="col-sm-3"></div>
						</div>
						<div class="col-sm-12 text-center">
							<span class="begin_run_btn" @click="createJob()">提交计算任务</span>
						</div>
					</div>
				</div>	
			</div>
		</div>
		<footerHtml></footerHtml>
		<!--遮罩层-->
		<div id="mask" v-if="seen" :style="{height: relHeight}"></div>
		<img src="../../assets/img/loading.gif" alt="loading" class="loading_img" v-show="loading"/>
		<!--重新选择数据-->
		<div class="bomb_box" v-if="bomb_data" style="width:800px;margin-left:-400px;">
			<p class="text-left">
				<span>已选数据</span>
				<span :title="details.title">{{details.title}}</span>
			</p>
			<table class="table table-striped table-hover table-bordered" id="detail_table" >  
	            <thead>  
	                <tr>  
	                    <th style="width:30%;">数据名称</th>  
	                    <th style="width:15%;">数据大小</th> 
	                    <th style="width:15%;">创建者</th> 
	                    <th style="width:15%;">列数</th> 
	                    <th style="width:15%;" >行数</th>
	                    <th style="width:10%;">操作</th>   	                       
	                </tr>  
	            </thead>  
	            <tbody>  
	            	<tr v-if="dataAll.data_all_list.length==0">
	                	<td colspan="6">暂时无数据</td>
	                </tr>
	            	<tr v-for="data_item in dataAll.data_all_list" class="text-left" v-else> 
	                    <td :title="data_item.title">{{data_item.title}}</td>  
	                    <td>{{data_item.size}}KB</td>  
	                    <td>{{data_item.creator}}</td>  
	                    <td>{{data_item.column_number}}</td>  
	                    <td>{{data_item.line_number}}</td>  
	                    <td>  
	                        <label class="input_label_beautify" style="margin:0">
						        <input class="input_radio" type="radio" name="dash_checkbox"  v-on:click="changeDataId(data_item.id)" :id="data_item.id">
						        <span class="input_checkbox input_radioInput"></span>
							</label>
	                    </td>  
	              	</tr> 	              	
	            </tbody>  
	        </table> 
	       	<v-pagination :total="dataAll.total"  :current-page='dataAll.current' @pagechange="pagechange" ></v-pagination>
			<p  class="text-right" style="margin-top:60px;">
				<button class="data_info_cancel btn" @click="bombBoxHide()">取消</button>
				<button class="btn data_edit_sure"  style="margin-left:40px;" @click="compSelection()">确定</button>
			</p>
		</div>
		<!--重新选择模板-->
		<div class="bomb_box" v-if="bomb_model" style="width:800px;margin-left:-400px;">
			<p class="text-left">
				<span>已选数据</span>
				<span :title="details.title">{{details.title}}</span>
			</p>				
			<table class="table table-striped table-hover table-bordered" id="detail_table" >  
	            <thead>  
	                <tr>  
	                    <th style="width:30%;">模型名称</th>  
	                    <th style="width:15%;">创建者</th> 
	                    <th style="width:15%;">是否要求数据标签</th>  
	                    <th style="width:15%;">需要特征列数</th>  
	                    <th style="width:15%;">可进行预测</th>  
	                    <th style="width:10%;">操作</th>   	                       
	                </tr>  
	            </thead>  
	            <tbody> 
	            	<tr v-if="modelAll.model_tem_all_list.length==0">
	                	<td colspan="6">暂时无模型</td>
	                </tr>
	            	<tr v-for="model_item in modelAll.model_tem_all_list" class="text-left" v-else> 
	                    <td :title="model_item.name">{{model_item.name}}</td>  
	                    <td>{{model_item.creator}}</td>  
	                    <td v-if="model_item.data_label==0">否</td>  
	                    <td v-else>是</td>
	                    <td>{{model_item.feature_number}}</td> 
	                    <td v-if="model_item.predictable==0">否</td>  
	                    <td v-else>是</td> 
	                    <td>  
	                        <label class="input_label_beautify" style="margin:0px;">
						        <input class="input_radio" type="radio" name="dash_checkbox_Tem" v-on:click="changeModelId(model_item.id,model_item.model_type )" :id="model_item.id">
						        <span class="input_checkbox input_radioInput"></span>
							</label>
	                    </td>  
	              	</tr> 	              	
	            </tbody>  
	        </table> 
	       	<v-pagination :total="modelAll.total"  :current-page='modelAll.current' @pagechange="pagechange2"></v-pagination>
			<p  class="text-right" style="margin-top:60px;">
				<button class="data_info_cancel btn" @click="bombBoxHide()">取消</button>
				<button class="btn data_edit_sure"  style="margin-left:40px;" @click="compSelectionModel()">确定</button>
			</p>
		</div>
	</div>
</template>

<script>
	//引入公共模块
	import headTop from '@/components/headTop'
	import footerHtml from '@/components/footerHtml'
	import pagination from '@/components/page'
	import selectCol from '@/components/selectCol'
	import modelTemplate from '@/components/model_template'
	import dragSpe from '@/components/drag_spe'
	import global_ from '@/components/global'

	import {urlDataDetail,urlDashDataList,urlCreaterJob,urlRunJob,urlDashModelsList,urlModelDetail} from '../../api/api'
	export default {
	    name: 'buildStep',   
	    data(){
	    	return {
	    		pagestate:-1 ,
	    		i:-1,
	    		job_id:'',
	    		change_data_id:'',
	    		change_model_id:'',
	    		change_model_type:'',
	    		dataAll:{	    			
		    		data_all_list:'',     		
	        		total:5,
	        		page_num:1,
	        		current:1,
	        		filter:0,
	    		},
	    		modelAll:{
	    			model_tem_all_list:'',       		
	        		total:5,
	        		page_num:1,
	        		current:1,
	        		filter:0
	    		},
	    		seen:false,
	    		already_chosen:false,
	    		createSuccess:false,
	    		createError:false,
	    		bomb_data:false,
	    		bomb_model:false,
	    		runStepThree:false,
	    		no_choose:true,
	    		missVal:false,
	    		onlyData:false,
	    		successDataTip:false,
	    		successModelTip:false,
	    		loading:false,
	    		drag_manual:false,
	    		drag_predict:false,
	    		details:{
	    			title:'',
	    			creator:'',
	    			create_time:'',
	    			column_number:'',
	    			line_number:'',
	    			col_detail:'',
	    			
	    		},
	    		model_tem_details:{
	    			name:'',
	    			creator:'',
	    			create_time:'',
	    			features_detail:'',
	    			feature_number:'',
	    			label_number:'',
	    			label_detail:'',
	    			param_spec:'',
	    			hyper_param_spec:''
	    			
	    		},
	    		selected: '0',
			   	options: [
			   	{ text: '忽略缺失值', value: '0' },
			    { text: '平均数填充', value: '1' },
			    { text: '中位数填充', value: '2' },
			    { text: '众数填充 ', value: '3' }
			   	],
			   	data_begin:1,
			   	data_end:'',
			   	check_only_data:'',
			   	check_miss_val:'',		   	
			   	//页面的高度
			   	relHeight:''
	    	}
	    },
	    components:{
	    	headTop,
	    	footerHtml,
	    	'v-pagination': pagination,
	    	selectCol,
	    	modelTemplate,
	    	dragSpe
	    	
	    },   
	    mounted(){
	    	//如果path是-2的话，代表是预测（拖拽整体有限制），如果是-1则是手动建模(拖拽只有标签有限制)
	    	this.pagestate = this.$route.params.path;				
	    },
	    methods: { 
	    	loadAllData(){	
				let sendData={
					page:this.dataAll.page_num,
					filter:this.dataAll.filter,
					owner:2
				};
        		//JOB表格数据
         		urlDashDataList(sendData).then(response => {
         			if(response.data.code==200){        				
		              	this.dataAll.data_all_list=response.data.data.items;
		            	this.dataAll.total=response.data.data.pagination*5;        				
         			}else{
         				alert('返回数据有误')
         			}
	           })
        	},
			loadAllModel(){
				(this.pagestate==-1) ? this.modelAll.filter=2 : this.modelAll.filter=1;
				let sendData={
					page:this.modelAll.page_num,
					filter:this.modelAll.filter,
					owner:2
				};				
        		//模型
         		urlDashModelsList(sendData).then(response => {
         			if(response.data.code==200){
		              	this.modelAll.model_tem_all_list=response.data.data.items;
		            	this.modelAll.total=response.data.data.pagination*5;        				
         			}else{
         				alert('返回数据有误')
         			}
	            }).catch(error => {
					if(error.response.data.code==401){
	            		localStorage.clear();
	            		this.$router.replace('/login');
					}
	            });
			},
	    	loadDataInfo(){
	    		if(this.$route.params.key!=-1){	    		
			    	let	sendData={
				  		id:this.$route.params.key
			    	};
			    	urlDataDetail(sendData).then(response => {
			  			if(response.data.code==200){	  				
			  				let resData=response.data.data;
				 			this.details.title=resData.title;
				    		this.details.line_number=resData.line_number;
				    		this.details.column_number=resData.column_number;
				    		this.details.create_time=resData.create_time;
				    		this.details.creator=resData.creator;
				    		this.details.col_detail=resData.col_detail;				    		
			  			}else if(response.data.code!=200){
			  				console.log('获取数据失败')
			  			}				    		
		     		}).catch(error => {
						if(error.response.data.code==401){
		            		localStorage.clear();
		            		this.$router.replace('/login');
						}
		            });
		    	}
	    	},
	    	loadTemModelInfo(){   		
		    	let	sendData={
			  		id:this.change_model_id,
			  		model_type:this.change_model_type
		    	};		    	
		    	urlModelDetail(sendData).then(response => {
		  			if(response.data.code==200){	  				
		  				let resData=response.data.data;
			 			this.model_tem_details.name=resData.name;
			    		this.model_tem_details.creator=resData.creator;;
			    		this.model_tem_details.feature_number=resData.feature_number;
			    		this.model_tem_details.label_number=resData.label_number;
			    		this.model_tem_details.create_time=resData.create_time;
			    		this.model_tem_details.features_detail=resData.features_detail;
			    		this.model_tem_details.label_detail=resData.label_detail;
			    		this.model_tem_details.param_spec=resData.param_spec;
			    		this.model_tem_details.hyper_param_spec=resData.hyper_param_spec;
			    		console.log(resData.hyper_param_spec)
			    		this.runStepThree=true;
			    		(this.pagestate==-1) ? (this.drag_manual=true,this.drag_predict=false) : (this.drag_predict=true,this.drag_manual=false);
		  			}else if(response.data.code!=200){
		  				console.log('获取数据失败')
		  			}				    		
		     	});		    	
	    	},
	    	showDataList(){
	    		this.relHeight=`${document.documentElement.scrollHeight}px`;	
	    		this.seen=true;
	    		this.bomb_data=true;
	    		this.loadAllData();
	    	},
	    	showModelList(){
	    		this.relHeight=`${document.documentElement.scrollHeight}px`;	
	    		this.seen=true;
	    		this.bomb_model=true;
	    		this.loadAllModel();
	    	},
	    	changeDataId(id){
	    		this.change_data_id=id;
	    	},
	    	changeModelId(id,model_type){
	    		this.change_model_id=id;
	    		this.change_model_type=model_type;
	    	},
	    	compSelection(){
	    		this.seen=false;
	    		this.bomb_data=false;
	    		this.successDataTip=true;
	    		this.$route.params.key=this.change_data_id;
	    		this.loadDataInfo();
	    	},
	    	compSelectionModel(){
	    		this.seen=false;
	    		this.bomb_model=false;
	    		this.successModelTip=true;
	    		this.already_chosen=true;
	    		this.no_choose=false;
	    		this.loadTemModelInfo();
	    	},	
	    	bombBoxHide(){
	    		this.seen=false;
	    		this.bomb_data=false;
	    		this.bomb_model=false;
				this.runJob=false;
	    	},
	    	updateShow(index){
	    		this.i=index;
	    	},
    	   	pagechange:function(currentPage){		    	
		      	this.dataAll.page_num=currentPage 
		    // ajax请求, 向后台发送 currentPage, 来获取对应的数据 
		      	this.loadAllData();
		    },
		    pagechange2:function(currentPage2){		    	
		      	this.modelAll.page_num=currentPage2;
		      	this.loadAllModel();
		    },
		    showCustom(){
				(this.check_miss_val==true) ? this.missVal=true : this.missVal=false;
		    },
		    showCustomData(){
				(this.check_only_data==true) ? this.onlyData=true : this.onlyData=false;
		    },
	    	createJob(){
	    		//job_type 1 手动建模 2智能建模(智能建模时候可不传) 3测试(测试时候可不传) 4预测，sendType 2是训练 3是预测
	    		let	nodeType='',
	    			jobType=1,
	    			sendNodes=[];
	    		(this.pagestate==-1) ? (nodeType=2) : (nodeType=3,jobType=4);
	    		let sendJson={
		    			name:this.model_tem_details.name,		    	
		    			type:nodeType,
		    			model_id:this.change_model_id,
		    			position:2,
		    			hyper_opt:'None',
		    			params:this.model_tem_details.param_spec,
		    			hyper_param:this.model_tem_details.hyper_param_spec
		    		};
	    		sendNodes.push(sendJson);	 			
	    		console.table(sendNodes);
	    		let	colArr = [];	    		
	    		if(this.pagestate==-1){
	    			let colLi = $('#foo').children('li');
	    			$.each(colLi,function(i,n){
		    			colArr.push($(n).attr('is_index'));		    			
		    		});
	    		}else if(this.pagestate==-2){
	    			let colLi = $('.drag_right_con').children('div');
	    			$.each(colLi,function(i,n){
		    			colArr.push($(n).children('ul').children('li').attr('is_index'))
		    		});
	    		}
	    		//检查右侧框里有空值没拖拽，应 return false;
	    		for(var i = 0 ;i<colArr.length;i++) {  
             		if(colArr[i] == "" || typeof(colArr[i]) == "undefined") {  
                     	alert('数据没有选择完整');
                     	return false;
             		}
         		}  
         		//把数组里面的字符串转成数字 eg:['1','2']=>[1,2]
           		var colArrEnd = colArr.map(function(item) {
				    var temp = parseInt(item)
				    if (temp === temp) {
				        return temp
				    }else
				    return item
				});
	    		let sendData={
		    			data_id:this.change_data_id || this.$route.params.key,	    			
		    			job_type:jobType,
		    			tag_col:$('#foospe').children('li').attr('is_index') || '',
						cols:colArrEnd,
						data_processing:this.selected,
		    			nodes:sendNodes
		    		};	
	    		urlCreaterJob(sendData).then(response => {
         			if(response.data.code==200){
         				this.createSuccess=true;
		              	this.job_id=response.data.data.job_id; 
						let sendDataRun={
							job_id:this.job_id
						}
		              	urlRunJob(sendDataRun).then(response => {
		         			if(response.data.code==200){
		         				this.relHeight=`${document.documentElement.scrollHeight}px`;		         				
		         				this.seen=true;
		         				this.loading=true;
		         				this.runJob=true;
		         				this.createSuccess=false;
								this.createError=false;
		         				this.linkSocket();
		         			}else{
		         				this.createError=true;
		         				alert('抱歉，返回数据有误')
		         			}
			           })
         			}else{
         				this.createError=true;
         				alert('抱歉，返回数据有误')
         			}
	            })

	    	},		   
			linkSocket(){				
				let socket = io.connect(global_.urlSocket),
		            user = localStorage.getItem('username');
		        socket.emit('join', {'room': user});
				let _selfRun=this;
		        socket.on('my_response', function(res) {		        	
		            //单播消息
		            if(res.type==3){
		            	if(res.code==0 && res.type==3){
		            		console.log('执行中')
		            		console.log(res.data)
		            	}else if(res.code==1 && res.type==3){	 
		            		//进入训练报告  模板-->报告
		            		_selfRun.seen=false;
		         			_selfRun.loading=false;
		            		_selfRun.runJob=false;
		            		_selfRun.$router.push({name:'templateReport',params: {id:_selfRun.job_id,node:-1}});		            		
		            	}else if(res.code==4 && res.type==3){	 
		            		//进入到预测报告  模型-->报告
		            		_selfRun.seen=false;
		            		_selfRun.loading=false;
		            		_selfRun.runJob=false;
		            		_selfRun.$router.push({name:'modelReport',params: {id:_selfRun.job_id,node:-1}})			            		
		            	}
		            }
		        });
				
		        //接收广播
		        socket.on('broadcast', function(res){
		            console.log(res.data);
		        });
			}
	  	},
	  	created(){
	  		this.loadDataInfo();  		
	  	}
	}
</script>

<style lang="css">
	@import "../../assets/css/base.css"
</style>
<style lang="css">
	@import "../../assets/css/buildStep.css"	
</style>
<style lang="css">
	@import "../../assets/css/data_details.css"
</style>